package com.tiance.demo.observer;

import java.util.HashSet;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;

/**
 * 自定义的Observable
 */
public class Publisher extends Observable {

    private ObserverEvent oe;

    private Set<Observer> observers = new HashSet<>();

    public Publisher(ObserverEvent oe) {
        this.oe = oe;
    }

    public ObserverEvent getObserverEvent() {
        return oe;
    }

    public boolean addSubscriber(Observer observer) {
        for (Object o : observers) {
            if (o == observer) {
                System.out.println("重复的监听者");
            }
        }

        if (observers.contains(observer)) {
            return false;
        }

        this.addObserver(observer);
        return observers.add(observer);
    }

    public void notifyWithData(ObserverData od) {
        this.setChanged();
        super.notifyObservers(od);
        this.clearChanged();
    }

}
